#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ubuntu 路由器自动配置脚本
支持 WAN/LAN 配置、DHCP、无线 AP、WiFi 客户端等功能的自动化配置
"""

import os
import sys
import yaml
import subprocess
import shutil
import argparse
import re
import time
from pathlib import Path
from typing import Dict, List, Optional

class RouterSetup:
    def __init__(self, config_file: str = "config.yaml"):
        self.config_file = config_file
        self.config = None
        self.base_dir = Path(__file__).parent
        self.etc_dir = Path("/etc/ubuntu-router")
        self.scripts_dir = self.base_dir / "scripts"
        
    def load_config(self) -> Dict:
        """加载配置文件"""
        config_path = self.base_dir / self.config_file
        if not config_path.exists():
            print(f"错误: 配置文件 {config_path} 不存在")
            print(f"请复制 config.yaml.example 为 config.yaml 并修改配置")
            sys.exit(1)
            
        with open(config_path, 'r', encoding='utf-8') as f:
            self.config = yaml.safe_load(f)
        return self.config
    
    def run_command(self, cmd: List[str], check: bool = True, timeout: Optional[int] = None) -> subprocess.CompletedProcess:
        """执行命令"""
        print(f"执行: {' '.join(cmd)}")
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
            if check and result.returncode != 0:
                print(f"错误: 命令执行失败")
                print(f"stdout: {result.stdout}")
                print(f"stderr: {result.stderr}")
                sys.exit(1)
            return result
        except subprocess.TimeoutExpired:
            print(f"错误: 命令执行超时（{timeout}秒）")
            if check:
                sys.exit(1)
            # 返回一个模拟的结果对象
            class TimeoutResult:
                def __init__(self):
                    self.returncode = -1
                    self.stdout = ""
                    self.stderr = f"命令执行超时（{timeout}秒）"
            return TimeoutResult()
    
    def check_root(self):
        """检查是否为 root 权限"""
        if os.geteuid() != 0:
            print("错误: 需要 root 权限运行此脚本")
            print("请使用: sudo python3 router_setup.py")
            sys.exit(1)
    
    def detect_interfaces(self) -> Dict[str, List[str]]:
        """自动检测网络接口"""
        print("正在检测网络接口...")
        result = self.run_command(["ip", "-br", "link", "show"])
        
        ethernets = []
        wireless = []
        
        for line in result.stdout.strip().split('\n'):
            if not line.strip():
                continue
            parts = line.split()
            ifname = parts[0]
            
            # 检测有线网卡
            if 'eth' in ifname or 'enp' in ifname or 'ens' in ifname:
                if 'wlan' not in ifname and 'wlp' not in ifname:
                    ethernets.append(ifname)
            # 检测无线网卡（支持 wlan、wlx、wlp 开头）
            elif 'wlan' in ifname or 'wlx' in ifname or 'wlp' in ifname:
                wireless.append(ifname)
        
        print(f"检测到有线网卡: {ethernets}")
        print(f"检测到无线网卡: {wireless}")
        
        return {
            'ethernets': ethernets,
            'wireless': wireless
        }
    
    def create_directories(self):
        """创建必要的目录"""
        dirs = [
            self.etc_dir,
            self.etc_dir / "wan",
            self.etc_dir / "lan",
            self.etc_dir / "wireless",
            self.etc_dir / "scripts"
        ]
        for d in dirs:
            d.mkdir(parents=True, exist_ok=True)
            print(f"创建目录: {d}")
    
    def setup_wan(self):
        """配置 WAN 口"""
        wan = self.config['wan']
        interface = wan['interface']
        mode = wan.get('mode', 'dhcp')
        
        print(f"\n配置 WAN 口: {interface}")
        
        netplan_config = {
            'network': {
                'version': 2,
                'renderer': 'networkd',
                'ethernets': {
                    interface: {}
                }
            }
        }
        
        if mode == 'dhcp':
            netplan_config['network']['ethernets'][interface] = {
                'dhcp4': True,
                'dhcp4-overrides': {
                    'route-metric': 100
                }
            }
        else:  # static
            netplan_config['network']['ethernets'][interface] = {
                'addresses': [f"{wan['static_ip']}/{wan.get('static_netmask', '255.255.255.0')}"],
                'gateway4': wan.get('static_gateway'),
                'nameservers': {
                    'addresses': wan.get('static_dns', ['8.8.8.8', '8.8.4.4'])
                }
            }
        
        # 保存 netplan 配置
        netplan_file = Path(f"/etc/netplan/01-wan-{interface}.yaml")
        with open(netplan_file, 'w') as f:
            yaml.dump(netplan_config, f, default_flow_style=False)
        # 设置文件权限为 600（netplan 要求）
        netplan_file.chmod(0o600)
        print(f"已创建 netplan 配置: {netplan_file}")
        
        # 应用配置
        self.run_command(["netplan", "apply"])
        print("WAN 口配置完成")
    
    def setup_lan_bridge(self):
        """配置 LAN 网桥"""
        lan = self.config['lan']
        interfaces = lan['interfaces']
        bridge_name = lan['bridge_name']
        router_ip = lan['router_ip']
        
        print(f"\n配置 LAN 网桥: {bridge_name}")
        
        # netplan 要求：在 bridges 中引用的接口必须先在使用 bridges 配置之前定义
        # 我们需要在 ethernets 中定义这些接口，但不给它们分配 IP（它们将属于网桥）
        ethernets_config = {}
        for iface in interfaces:
            ethernets_config[iface] = {
                'dhcp4': False,
                'dhcp6': False
            }
        
        netplan_config = {
            'network': {
                'version': 2,
                'renderer': 'networkd',
                'ethernets': ethernets_config,
                'bridges': {
                    bridge_name: {
                        'addresses': [f"{router_ip}/24"],
                        'interfaces': interfaces,
                        'parameters': {
                            'stp': False,
                            'forward-delay': 0
                        }
                    }
                }
            }
        }
        
        # 保存 netplan 配置
        netplan_file = Path(f"/etc/netplan/02-lan-bridge.yaml")
        with open(netplan_file, 'w') as f:
            yaml.dump(netplan_config, f, default_flow_style=False)
        # 设置文件权限为 600（netplan 要求）
        netplan_file.chmod(0o600)
        print(f"已创建 netplan 配置: {netplan_file}")
        
        # 应用配置
        self.run_command(["netplan", "apply"])
        print("LAN 网桥配置完成")
    
    def setup_dhcp(self):
        """配置 DHCP 服务"""
        dhcp = self.config['dhcp']
        if not dhcp.get('enabled', True):
            print("DHCP 服务未启用，跳过配置")
            return
        
        lan = self.config['lan']
        bridge_name = lan['bridge_name']
        router_ip = lan['router_ip']
        
        print(f"\n配置 DHCP 服务")
        
        dnsmasq_config = f"""interface={bridge_name}
bind-interfaces
dhcp-range={dhcp['range_start']},{dhcp['range_end']},255.255.255.0,{dhcp['lease_time']}
dhcp-option=3,{router_ip}
dhcp-option=6,{','.join(dhcp['dns_servers'])}
cache-size=1000
domain-needed
bogus-priv
"""
        
        # 保存 dnsmasq 配置
        dnsmasq_file = Path("/etc/dnsmasq.conf")
        
        # 备份原配置
        if dnsmasq_file.exists():
            backup_file = dnsmasq_file.with_suffix('.conf.backup')
            shutil.copy2(dnsmasq_file, backup_file)
            print(f"已备份原配置: {backup_file}")
        
        with open(dnsmasq_file, 'w') as f:
            f.write(dnsmasq_config)
        print(f"已创建 dnsmasq 配置: {dnsmasq_file}")
        
        # 创建 systemd override 确保 dnsmasq 在网桥创建后启动
        self.setup_dnsmasq_service_dependency(bridge_name)
        
        # 重启 dnsmasq
        self.run_command(["systemctl", "restart", "dnsmasq"], check=False)
        self.run_command(["systemctl", "enable", "dnsmasq"])
        print("DHCP 服务配置完成")
    
    def setup_nat(self):
        """配置 NAT 转发"""
        wan = self.config['wan']
        wan_interface = wan['interface']
        
        print(f"\n配置 NAT 转发")
        
        # 启用 IP 转发
        sysctl_file = Path("/etc/sysctl.d/99-router.conf")
        sysctl_content = """net.ipv4.ip_forward=1
"""
        with open(sysctl_file, 'w') as f:
            f.write(sysctl_content)
        
        self.run_command(["sysctl", "-p", str(sysctl_file)])
        print("已启用 IP 转发")
        
        # 配置 iptables NAT 规则
        # 先清除可能存在的旧规则
        self.run_command(["iptables", "-t", "nat", "-F", "POSTROUTING"], check=False)
        
        # 添加 NAT 规则
        self.run_command([
            "iptables", "-t", "nat", "-A", "POSTROUTING",
            "-o", wan_interface, "-j", "MASQUERADE"
        ])
        
        # 保存 iptables 规则
        self.run_command(["netfilter-persistent", "save"], check=False)
        # 如果 netfilter-persistent 不存在，尝试使用 iptables-persistent
        if not shutil.which("netfilter-persistent"):
            self.run_command(["sh", "-c", "iptables-save > /etc/iptables/rules.v4"], check=False)
        
        print("NAT 转发配置完成")
    
    def setup_wireless_ap(self):
        """配置无线 AP"""
        ap = self.config.get('wireless_ap', {})
        if not ap.get('enabled', False):
            print("无线 AP 未启用，跳过配置")
            return
        
        lan = self.config['lan']
        bridge_name = lan['bridge_name']
        
        print(f"\n配置无线 AP")
        
        # 获取物理无线网卡名称（配置文件中）
        physical_interface = ap['interface']
        ssid = ap['ssid']
        password = ap['password']
        channel = ap.get('channel', 'auto')
        hw_mode = ap.get('hw_mode', 'g')
        encryption = ap.get('encryption', 'WPA2')
        
        # 检查物理接口是否存在
        result = self.run_command(["ip", "link", "show", physical_interface], check=False)
        if result.returncode != 0:
            print(f"错误: 物理接口 {physical_interface} 不存在")
            return
        
        # 注意：AP 使用虚拟接口（如 wlp8s0_ap），WiFi 客户端使用物理接口（如 wlp8s0）
        # 它们使用不同的接口，理论上可以共存，无需停止客户端服务
        
        # 确保 NetworkManager 不管理此接口（如果存在）
        if shutil.which("nmcli"):
            self.run_command(["nmcli", "device", "set", physical_interface, "managed", "no"], check=False)
        
        # 检查 iw 命令是否存在
        if not shutil.which("iw"):
            print("错误: iw 命令未找到，请安装: apt install iw")
            return
        
        # 创建虚拟 AP 接口名称（参考 wifi_manager.py 的命名方式）
        ap_interface = f"{physical_interface}ap"
        print(f"基于物理接口 {physical_interface} 创建虚拟 AP 接口: {ap_interface}")
        
        # 检查虚拟接口是否已存在
        check_result = self.run_command(["ip", "link", "show", ap_interface], check=False)
        if check_result.returncode == 0:
            print(f"虚拟接口 {ap_interface} 已存在，跳过创建")
        else:
            # 虚拟接口不存在，需要创建
            print(f"正在创建虚拟 AP 接口: {ap_interface}")
            
            # 获取物理设备名称（phy）
            phy_result = self.run_command(["iw", "dev", physical_interface, "info"], check=False)
            if phy_result.returncode != 0:
                print(f"错误: 无法获取接口 {physical_interface} 的信息")
                return
            
            # 提取 phy 名称（如 phy0）
            phy_name = None
            for line in phy_result.stdout.split('\n'):
                if 'wiphy' in line:
                    phy_match = re.search(r'wiphy\s+(\d+)', line)
                    if phy_match:
                        phy_name = f"phy{phy_match.group(1)}"
                        break
            
            if not phy_name:
                print(f"错误: 无法从接口 {physical_interface} 提取物理设备名称（phy）")
                return
            
            print(f"使用物理设备 {phy_name} 创建虚拟接口...")
            
            # 确保物理接口处于 UP 状态（创建虚拟接口需要）
            self.run_command(["ip", "link", "set", physical_interface, "up"], check=False)
            time.sleep(0.5)
            
            # 使用 phy 方式创建虚拟接口（更可靠）
            create_result = self.run_command([
                "iw", "phy", phy_name, "interface", "add", ap_interface, "type", "__ap"
            ], check=False)
            
            if create_result.returncode != 0:
                print(f"错误: 创建虚拟接口失败")
                if create_result.stderr:
                    print(f"错误信息: {create_result.stderr}")
                if create_result.stdout:
                    print(f"输出信息: {create_result.stdout}")
                return
            
            # 验证虚拟接口是否创建成功
            time.sleep(0.5)
            verify_result = self.run_command(["ip", "link", "show", ap_interface], check=False)
            if verify_result.returncode != 0:
                print(f"错误: 虚拟接口创建后验证失败，AP 接口未创建成功")
                return
            
            print(f"✓ 虚拟接口 {ap_interface} 创建成功")
        
        # 启用虚拟接口并添加到网桥
        self.run_command(["ip", "link", "set", ap_interface, "up"], check=False)
        self.run_command(["ip", "link", "set", ap_interface, "master", bridge_name], check=False)
        
        # 创建开机自动创建虚拟接口的 systemd 服务
        self.create_ap_interface_service(physical_interface, ap_interface, bridge_name)
        
        # 使用虚拟接口作为 hostapd 接口
        hostapd_interface = ap_interface
        
        # 生成 hostapd 配置
        # 基础接口配置
        hostapd_config = f"""interface={hostapd_interface}
driver=nl80211
ssid={ssid}
hw_mode={hw_mode}
"""
        
        # 信道配置：优先使用固定信道，避免 ACS 失败
        if channel == 'auto':
            # 如果未指定信道，默认使用信道 6（2.4GHz 常用信道）
            # 也可以使用 channel=0 启用 ACS，但可能不稳定
            print("警告: channel 设置为 auto，将使用默认信道 6（避免 ACS 失败）")
            print("建议: 在配置文件中明确指定信道号（1-13）以获得最佳稳定性")
            hostapd_config += "channel=6\n"
        else:
            try:
                channel_num = int(channel)
                if 1 <= channel_num <= 13:
                    hostapd_config += f"channel={channel_num}\n"
                else:
                    print(f"警告: 信道号 {channel_num} 超出范围（1-13），使用默认信道 6")
                    hostapd_config += "channel=6\n"
            except ValueError:
                print(f"警告: 无效的信道配置 '{channel}'，使用默认信道 6")
                hostapd_config += "channel=6\n"
        
        # 添加国家代码（必须，否则可能无法启动）
        hostapd_config += "country_code=CN\n"
        
        # 添加基本认证和 MAC 地址控制
        hostapd_config += """macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
"""
        
        # 加密配置
        if encryption in ['WPA2', 'WPA3']:
            if encryption == 'WPA2':
                hostapd_config += f"""wpa=2
wpa_passphrase={password}
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
"""
            else:  # WPA3
                hostapd_config += f"""wpa=2
wpa_passphrase={password}
wpa_key_mgmt=WPA-PSK-SHA256
rsn_pairwise=CCMP
"""
        
        # 网桥配置
        hostapd_config += f"bridge={bridge_name}\n"
        
        # 性能优化配置（仅对 2.4GHz 802.11n/g）
        if hw_mode in ['g', 'n']:
            hostapd_config += """ieee80211n=1
wmm_enabled=1
"""
        
        # 保存 hostapd 配置
        hostapd_file = Path("/etc/hostapd/hostapd.conf")
        hostapd_file.parent.mkdir(parents=True, exist_ok=True)
        
        with open(hostapd_file, 'w') as f:
            f.write(hostapd_config)
        print(f"已创建 hostapd 配置: {hostapd_file}")
        
        # 配置 hostapd 服务
        hostapd_service_file = Path("/etc/default/hostapd")
        with open(hostapd_service_file, 'w') as f:
            f.write(f"DAEMON_CONF={hostapd_file}\n")
            f.write("DAEMON_OPTS=\n")  # 修复环境变量警告
        
        # 停止可能存在的 hostapd 进程（为重新配置做准备）
        self.run_command(["systemctl", "stop", "hostapd"], check=False)
        
        # 注意：跳过 hostapd -t 测试，因为该命令在测试时会尝试访问硬件，可能会卡住
        # 直接启动 hostapd 服务，让服务启动时的验证来检查配置是否正确
        
        # 启动 hostapd 服务
        self.run_command(["systemctl", "enable", "hostapd"])
        start_result = self.run_command(["systemctl", "start", "hostapd"], check=False)
        
        if start_result.returncode == 0:
            # 等待 hostapd 启动（使用固定信道，不需要等待 ACS）
            wait_time = 4
            print(f"等待 hostapd 启动完成（{wait_time} 秒）...")
            time.sleep(wait_time)
            
            # 检查 hostapd 进程是否运行（参考 wifi_manager.py 的方式）
            pgrep_result = self.run_command(["pgrep", "-f", f"hostapd.*{hostapd_interface}"], check=False)
            if pgrep_result.returncode == 0:
                # hostapd 进程存在
                pids = pgrep_result.stdout.strip().split('\n')
                print(f"✓ hostapd 进程已运行（PID: {', '.join(pids)}）")
                
                # 检查 systemd 服务状态
                status_result = self.run_command(["systemctl", "status", "hostapd", "--no-pager"], check=False)
                status_output = status_result.stdout
                
                if "active (running)" in status_output:
                    print("✓ 无线 AP 已成功启动（systemd 服务正常运行）")
                else:
                    print("⚠ systemd 服务状态异常，但 hostapd 进程在运行")
                    print(f"服务状态: {status_output[:200]}")
                
                # 显示接口状态
                interface_check = self.run_command(["ip", "link", "show", hostapd_interface], check=False)
                if interface_check.returncode == 0:
                    print(f"✓ 虚拟接口 {hostapd_interface} 状态正常")
                    # 检查接口是否处于 UP 状态
                    if "state UP" in interface_check.stdout or "UP" in interface_check.stdout:
                        print(f"✓ 接口 {hostapd_interface} 已启用")
                
                # 检查 hostapd 日志确认 AP 已启用
                log_result = self.run_command(["journalctl", "-u", "hostapd", "-n", "20", "--no-pager"], check=False)
                log_output = log_result.stdout
                if "AP-ENABLED" in log_output or "interface state" in log_output:
                    print("✓ hostapd 日志显示 AP 已启用")
                elif any(keyword in log_output.lower() for keyword in ["error", "failed", "could not"]):
                    print("⚠ hostapd 日志中发现错误信息")
                    # 显示错误行
                    for line in log_output.split('\n'):
                        if any(keyword in line.lower() for keyword in ["error", "failed", "could not"]):
                            print(f"   {line.strip()}")
            else:
                # hostapd 进程不存在，启动失败
                print("✗ hostapd 进程未运行，启动失败")
                
                # 检查 systemd 服务状态
                status_result = self.run_command(["systemctl", "status", "hostapd", "--no-pager"], check=False)
                print("\n服务状态:")
                print(status_result.stdout[:300])
                
                # 获取详细日志
                log_result = self.run_command(["journalctl", "-u", "hostapd", "-n", "30", "--no-pager"], check=False)
                print("\n最近日志:")
                print(log_result.stdout)
                
                print("\n请检查:")
                print(f"  systemctl status hostapd")
                print(f"  journalctl -u hostapd -n 50")
                print(f"  ip link show {hostapd_interface}")
                print(f"  iw dev {hostapd_interface} info")
        else:
            print("✗ 无线 AP 启动失败")
            
            # 获取详细错误信息
            log_result = self.run_command(["journalctl", "-u", "hostapd", "-n", "30", "--no-pager"], check=False)
            print("\n错误日志:")
            print(log_result.stdout)
            
            print("\n请检查:")
            print(f"  systemctl status hostapd")
            print(f"  journalctl -u hostapd -n 50")
            print(f"  检查接口状态: ip link show {hostapd_interface}")
            print(f"  检查接口信息: iw dev {hostapd_interface} info")
        
        print("无线 AP 配置完成")
    
    def setup_wireless_client(self):
        """配置 WiFi 客户端"""
        client = self.config.get('wireless_client', {})
        if not client.get('enabled', False):
            print("WiFi 客户端未启用，跳过配置")
            return
        
        print(f"\n配置 WiFi 客户端")
        
        interface = client['interface']
        networks = client.get('networks', [])
        
        wpa_config = ""
        for i, net in enumerate(networks):
            wpa_config += f"""network={{
    ssid="{net['ssid']}"
    psk="{net['password']}"
    priority={net.get('priority', i+1)}
}}
"""
        
        # 保存 wpa_supplicant 配置
        wpa_file = Path("/etc/wpa_supplicant/wpa_supplicant.conf")
        wpa_file.parent.mkdir(parents=True, exist_ok=True)
        
        wpa_header = f"""ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=netdev
update_config=1
country=CN

"""
        
        with open(wpa_file, 'w') as f:
            f.write(wpa_header + wpa_config)
        print(f"已创建 wpa_supplicant 配置: {wpa_file}")
        
        # 启动 wpa_supplicant
        self.run_command(["systemctl", "restart", f"wpa_supplicant@{interface}"], check=False)
        self.run_command(["systemctl", "enable", f"wpa_supplicant@{interface}"])
        print("WiFi 客户端配置完成")
    
    def setup_mdns(self):
        """配置 mDNS 服务"""
        system = self.config.get('system', {})
        if not system.get('enable_mdns', True):
            print("mDNS 服务未启用，跳过配置")
            return
        
        hostname = system.get('hostname', 'ubunturouter')
        
        print(f"\n配置 mDNS 服务")
        
        # 设置主机名
        self.run_command(["hostnamectl", "set-hostname", hostname])
        
        # 配置 avahi
        avahi_file = Path("/etc/avahi/avahi-daemon.conf")
        if avahi_file.exists():
            # 备份原配置
            backup_file = avahi_file.with_suffix('.conf.backup')
            if not backup_file.exists():
                shutil.copy2(avahi_file, backup_file)
            
            # 确保启用 IPv4 和反射器
            # 这里只是启用服务，具体配置保持默认即可
        
        # 启动 avahi
        self.run_command(["systemctl", "restart", "avahi-daemon"], check=False)
        self.run_command(["systemctl", "enable", "avahi-daemon"])
        print("mDNS 服务配置完成")
    
    def setup_dnsmasq_service_dependency(self, bridge_name: str):
        """配置 dnsmasq 服务依赖，确保在网桥创建后启动"""
        print(f"\n配置 dnsmasq 服务依赖（确保网桥 {bridge_name} 创建后启动）...")
        
        # 创建 systemd override 目录
        override_dir = Path("/etc/systemd/system/dnsmasq.service.d")
        override_dir.mkdir(parents=True, exist_ok=True)
        
        # 创建 override 配置文件
        override_file = override_dir / "wait-for-bridge.conf"
        override_content = f"""[Unit]
# 确保在网桥接口创建后启动
After=network-online.target systemd-networkd.service
Wants=network-online.target
# 等待网桥接口存在
Requires=network-online.target

[Service]
# 添加启动前检查，确保网桥接口存在
ExecStartPre=/bin/bash -c 'until ip link show {bridge_name} >/dev/null 2>&1; do sleep 0.5; done'
# 添加启动延迟，确保网桥完全就绪
ExecStartPre=/bin/sleep 2
"""
        
        with open(override_file, 'w') as f:
            f.write(override_content)
        
        print(f"已创建 dnsmasq override 配置: {override_file}")
        
        # 重新加载 systemd
        self.run_command(["systemctl", "daemon-reload"])
        print("✓ dnsmasq 服务依赖配置完成")
    
    def create_ap_interface_service(self, physical_interface: str, ap_interface: str, bridge_name: str):
        """创建开机自动创建虚拟 AP 接口的 systemd 服务"""
        print(f"\n创建开机自动创建虚拟 AP 接口的服务...")
        
        # 创建启动脚本
        script_path = Path("/usr/local/bin/create-ap-interface.sh")
        script_content = f"""#!/bin/bash
# 开机自动创建虚拟 AP 接口脚本

PHYSICAL_INTERFACE="{physical_interface}"
AP_INTERFACE="{ap_interface}"
BRIDGE_NAME="{bridge_name}"

# 检查虚拟接口是否已存在
if ip link show "$AP_INTERFACE" &>/dev/null; then
    echo "虚拟接口 $AP_INTERFACE 已存在，跳过创建"
    exit 0
fi

# 检查物理接口是否存在
if ! ip link show "$PHYSICAL_INTERFACE" &>/dev/null; then
    echo "错误: 物理接口 $PHYSICAL_INTERFACE 不存在"
    exit 1
fi

# 确保物理接口 UP
ip link set "$PHYSICAL_INTERFACE" up 2>/dev/null
sleep 0.5

# 获取 phy 名称
PHY_NAME=$(iw dev "$PHYSICAL_INTERFACE" info 2>/dev/null | grep -oP 'wiphy\\s+\\K\\d+')
if [ -z "$PHY_NAME" ]; then
    echo "错误: 无法获取物理设备名称"
    exit 1
fi

# 创建虚拟接口
iw phy phy$PHY_NAME interface add "$AP_INTERFACE" type __ap 2>&1
if [ $? -ne 0 ]; then
    echo "错误: 创建虚拟接口失败"
    exit 1
fi

# 等待接口创建
sleep 0.5

# 验证接口是否创建成功
if ! ip link show "$AP_INTERFACE" &>/dev/null; then
    echo "错误: 虚拟接口创建后验证失败"
    exit 1
fi

# 启用接口
ip link set "$AP_INTERFACE" up 2>/dev/null

# 添加到网桥（如果网桥存在）
if ip link show "$BRIDGE_NAME" &>/dev/null; then
    ip link set "$AP_INTERFACE" master "$BRIDGE_NAME" 2>/dev/null
fi

echo "虚拟接口 $AP_INTERFACE 创建成功"
exit 0
"""
        
        # 保存脚本
        with open(script_path, 'w') as f:
            f.write(script_content)
        script_path.chmod(0o755)
        print(f"已创建脚本: {script_path}")
        
        # 创建 systemd 服务
        service_content = f"""[Unit]
Description=Create Virtual AP Interface
After=network.target
Before=hostapd.service
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/create-ap-interface.sh
RemainAfterExit=yes
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
"""
        
        service_file = Path("/etc/systemd/system/create-ap-interface.service")
        with open(service_file, 'w') as f:
            f.write(service_content)
        print(f"已创建 systemd 服务: {service_file}")
        
        # 重新加载 systemd 并启用服务
        self.run_command(["systemctl", "daemon-reload"])
        self.run_command(["systemctl", "enable", "create-ap-interface.service"])
        print("✓ 已启用开机自动创建虚拟接口服务")
    
    def setup_all(self):
        """执行所有配置"""
        print("=" * 60)
        print("Ubuntu 路由器自动配置")
        print("=" * 60)
        
        self.check_root()
        self.load_config()
        self.create_directories()
        
        # 检测接口
        detected = self.detect_interfaces()
        print(f"\n建议检查配置中的接口名称是否与实际检测到的接口匹配")
        
        try:
            self.setup_wan()
            self.setup_lan_bridge()
            self.setup_dhcp()
            self.setup_nat()
            self.setup_wireless_ap()
            self.setup_wireless_client()
            self.setup_mdns()
            
            print("\n" + "=" * 60)
            print("配置完成！")
            print("=" * 60)
            print("\n建议执行以下操作:")
            print("1. 检查网络接口状态: ip addr show")
            print("2. 检查服务状态: systemctl status dnsmasq hostapd")
            print("3. 测试 NAT 转发: 从 LAN 口设备访问公网")
            print("4. 重启系统以确保所有配置生效")
            
        except Exception as e:
            print(f"\n配置过程中出现错误: {e}")
            import traceback
            traceback.print_exc()
            sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description='Ubuntu 路由器自动配置工具')
    parser.add_argument('-c', '--config', default='config.yaml',
                       help='配置文件路径 (默认: config.yaml)')
    parser.add_argument('--detect-only', action='store_true',
                       help='仅检测网络接口')
    
    args = parser.parse_args()
    
    setup = RouterSetup(config_file=args.config)
    
    if args.detect_only:
        setup.check_root()
        setup.detect_interfaces()
    else:
        setup.setup_all()


if __name__ == '__main__':
    main()

